<template>
  <n-card :border="false">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：1.设置分销收益佣金比例、开启、禁用 &nbsp;&nbsp;&nbsp; 2.同一类型只能添加一个
    </n-alert>
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="searchParam" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="类型">
          <n-select v-model:value="searchParam.type" :options="typeOptions" style="width: 180px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(searchParam.type=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list" :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="searchParam"
                list-url="dist/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['vip:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <!--  新增、修改数据  -->
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改分销设置':'新增分销设置'" :mask-closable="false"
             :show-icon="false" preset="dialog" style="width:510px" @after-leave="closeAddEditModel">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              label-width="auto" label-placement="left">
        <n-form-item label="类型" path="type">
          <n-select v-model:value="addEditForm.type" :options="typeOptions" clearable/>
        </n-form-item>
        <n-form-item label="邀请下级" path="status">
          <n-radio-group v-model:value="addEditForm.status" name="statusgroup">
            <n-radio :value="0" label="关闭"/>
            <n-radio :value="1" label="开启"/>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="收益状态" path="comRevStatus">
          <n-radio-group v-model:value="addEditForm.comRevStatus" name="comRevStatusgroup">
            <n-radio :value="0" label="关闭"/>
            <n-radio :value="1" label="开启"/>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="收益比例(%)" path="ordersRate">
          <n-input-group>
            <n-input-number v-model:value="addEditForm.ordersRate" :show-button="false" placeholder="请输入收益比例"
                        :min="0" :max="1" :precision="4"   clearable/>
            <n-input-group-label>%</n-input-group-label>
          </n-input-group>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>
<script setup lang="ts">
import {ref, onBeforeMount, h, reactive} from 'vue'
import {FormInst, NPopconfirm, NTag, SelectOption, useMessage} from 'naive-ui'
import {delRequest, getRequest, postPutRequest} from '@/api/data.ts'
import SearchButtonGroup from '@components/SearchButtonGroup';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import DataTable from '@components/DataTable'
import {AddSharp} from "@vicons/material";

const message = useMessage()
//类型数据
const typeOptions = ref<SelectOption[]>([])

const searchParam = ref<{ type: number | null }>({
  type: null,
})
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '类型',
    key: 'typeName',
    width: 100,
  }, {
    title: '收益比例(%)',
    key: 'ordersRate',
    width: 100,
    align: 'center',
    render(row: { ordersRate: number }) {
      return h('span', null, {default: () => (row.ordersRate?.toFixed(4))});
    }
  }, {
    title: '邀请下级',
    key: 'status',
    width: 100,
    align: 'center',
    render(row: { status: number }) {
      const enabled_color = row.status ? 'success' : 'default';
      const enabled_text = row.status ? '开启' : '关闭';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  }, {
    title: '收益状态',
    key: 'comRevStatus',
    width: 100,
    align: 'center',
    render(row: { comRevStatus: number }) {
      const enabled_color = row.comRevStatus ? 'success' : 'default';
      const enabled_text = row.comRevStatus ? '开启' : '关闭';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  },
  {
    title: '创建时间',
    key: 'createTime',

  }
  // , {
  //   title: '更新时间',
  //   key: 'updateTime',
  // },
])
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['vip:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前设置吗？',
          },
          permission: ['vip:del']
        },
      ]
    });
  },
});
//新增、修改数据表单
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  type: null,
  status: 0,
  comRevStatus: 0,
  ordersRate: null,
})
const addEditFormRules = ref({
  type: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择类型'
  }
})
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.type = record.type;
  addEditForm.value.status = record.status;
  addEditForm.value.comRevStatus = record.comRevStatus;
  addEditForm.value.ordersRate = record.ordersRate;
  addEditModel.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('dist/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.type = null;
  addEditForm.value.status = 0;
  addEditForm.value.comRevStatus = 0;
  addEditForm.value.ordersRate = null;
  handelSubmitLoading.value = false;
}
//提交新增、修改数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'dist/edit' : 'dist/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
//获取类型
const get_types = async () => {
  await getRequest('dist/get_types').then((result: ResponseResult) => {
    const {data} = result;
    typeOptions.value = data;
  })
}
onBeforeMount(() => {
  get_types();
})
</script>

<style scoped lang="scss">

</style>